package cn.onesdream.app.api.service.Impl;

import cn.onesdream.app.api.service.ArticleService;
import cn.onesdream.app.dao.entity.Article;
import cn.onesdream.app.dao.entity.User;
import cn.onesdream.app.dao.mapper.ArticleMapper;
import cn.onesdream.app.dao.mapper.ArticleTypeMapper;
import cn.onesdream.app.dao.mapper.UserMapper;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author
 * @date 2020/11/27 17:55
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ArticleTypeMapper articleTypeMapper;

    @Override
    public Article changeArticleInfo(Integer articleId, String title, String content, MultipartFile[] pictures) throws IOException {
        String account = SecurityContextHolder.getContext().getAuthentication().getName();
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!path.exists()) {
            path = new File("");
        }
        File upload = new File(path.getAbsolutePath(),"static/articleImg/");
        if(!upload.exists()) {
            upload.mkdirs();
        }
        String prefix = "/articleImg_";
        String httpUrl = "https://app.onesdream.cn/smallPlanet/static/articleImg/";
        List<String> remoteImgUrls = new ArrayList<>();
        for(int i = 0; i < pictures.length; i++){
            String originalFilename = pictures[i].getOriginalFilename();
            String fileName =  prefix + account +  System.currentTimeMillis() + "_" + (i+1) + originalFilename.substring(originalFilename.lastIndexOf("."));
            String allFileName = upload + fileName;
            File imgFile = new File(allFileName);
            pictures[i].transferTo(imgFile.getAbsoluteFile());
            String remoteImgUrl = httpUrl + fileName;
            remoteImgUrls.add(remoteImgUrl);
        }
        //更新数据库文章信息
        UpdateWrapper<Article> articleUpdateWrapper = new UpdateWrapper<>();
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setCoverUrl(JSON.toJSONString(remoteImgUrls));
        articleUpdateWrapper.lambda()
                .eq(Article::getId, articleId);
        baseMapper.update(article, articleUpdateWrapper);
        article = getArticle(articleId);
        return article;
    }

    @Override
    public List<Article> getArticleByType(Byte typeId, Byte count) {
        //随机查找字段type_id为typeId的count条有效文章数据
        String sql = "select a.id from (select id from article where type_id = " + typeId
                + " and active = 1 order by rand() limit "+ count +")as a";
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.inSql("id", sql);
        List<Article> articleList = baseMapper.selectList(wrapper);
        return articleList;
    }

    @Override
    public Article getArticle(Integer articleId) {
        Article article = baseMapper.selectById(articleId);
        return article;
    }

    @Override
    public void addArticle(Integer userId, String title, String content, MultipartFile[] pictures, Byte typeId) throws IOException {
        String account = SecurityContextHolder.getContext().getAuthentication().getName();
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!path.exists()) {
            path = new File("");
        }
        File upload = new File(path.getAbsolutePath(),"static/articleImg/");
        if(!upload.exists()) {
            upload.mkdirs();
        }
        String prefix = "/articleImg_";
        String httpUrl = "https://app.onesdream.cn/smallPlanet/static/articleImg/";
        List<String> remoteImgUrls = new ArrayList<>();
        for(int i = 0; i < pictures.length; i++){
            String originalFilename = pictures[i].getOriginalFilename();
            String fileName =  prefix + account +  System.currentTimeMillis() + "_" + (i+1) + originalFilename.substring(originalFilename.lastIndexOf("."));
            String allFileName = upload + fileName;
            File imgFile = new File(allFileName);
            pictures[i].transferTo(imgFile.getAbsoluteFile());
            String remoteImgUrl = httpUrl + fileName;
            remoteImgUrls.add(remoteImgUrl);
        }
        Article article = new Article();
        article.setContent(content);
        article.setTitle(title);
        article.setCoverUrl(JSON.toJSONString(remoteImgUrls));
        article.setUserId(userId);
        article.setTypeId(typeId);
        baseMapper.insert(article);
    }

}
